package com.pubinfo.passbook.api.controller.auth;

import com.pubinfo.passbook.common.entity.TEnginePlaceholderVar;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.model.dto.engine.EngineVariableParam;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.base.MyPage;
import com.pubinfo.passbook.common.service.engine.EngineComputePlaceHolderVarService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author zhouch
 * @date 2021/12/20 16:47
 */
@Api(tags = "计算引擎-变量占位符管理")
@RestController
@RequestMapping("/engine/placeholder/variable")
public class EngineVariableController {

    @Resource
    EngineComputePlaceHolderVarService varService;

    @PostMapping("/page")
    @ApiOperation("分页查询")
    public JsonResult<MyPage<TEnginePlaceholderVar>> page(@RequestBody @Valid EngineVariableParam param) {
        return JsonResult.page(varService.page(param));
    }

    @PostMapping("/save")
    @ApiOperation("保存")
    public JsonResult<Boolean> save(@RequestBody @Valid TEnginePlaceholderVar varInfo) {
        if (varInfo.getId() != null) {
            throw new ServiceException("ID字段存在");
        }

        if (varService.existSymbol(varInfo.getSymbol())) {
            throw new ServiceException("标识符已经存在了");
        }

        return JsonResult.success(varService.save(varInfo));
    }

    @PostMapping("/update")
    @ApiOperation("更新")
    public JsonResult<Boolean> update(@RequestBody @Valid TEnginePlaceholderVar varInfo) {
        if (varInfo.getId() == null) {
            throw new ServiceException("ID字段不存在");
        }

        if (varService.existSymbol(varInfo.getSymbol())) {
            if (!varService.getBySymbol(varInfo.getSymbol()).getId().equals(varInfo.getId())) {
                throw new ServiceException("标识符已经存在了, 无法修改");
            }
        }

        return JsonResult.success(varService.updateById(varInfo));
    }

    @GetMapping("/remove/{id}")
    @ApiOperation("删除")
    public JsonResult<Boolean> remove(@PathVariable("id") Integer chainId) {
        return JsonResult.success(varService.removeById(chainId));
    }

    @GetMapping("/get/{id}")
    @ApiOperation("详情")
    public JsonResult<TEnginePlaceholderVar> get(@PathVariable("id") Integer id) {
        return JsonResult.success(varService.getById(id));
    }
}
